package krillr.Modules;
import krillr.Util.*;
import java.awt.Color;
import java.awt.geom.*;

public class StandardMover extends Module {
    private Point2d robotLocation = new Point2d(100,100);
    private Point2d enemyLocation = new Point2d(400,400);
    private double enemyDistance = 400;
    private double enemyAbsoluteBearing = 180;
    private double movementLateralAngle = 0.2;
    private double timeSinceLastScan = 0;
    private double lastEnemyEnergy = 100;
    private double timeSinceLastChange = 0;
    public StandardMover(KrillBot b) {
        bot = b;
    }
    public void run() {
        if(timeSinceLastChange != 0) {
            timeSinceLastChange--;
            return;
        }
        bot.setTarget(bot.findTarget());
        if(bot.target == null)
            return;
        if(bot.target.hasFired()) {
            bot.setTurnLeft(KrillUtil.bestAngle(90 - bot.target.lastKnownBearing()));
        }
        Point2d robotLocation = bot.getLocation();
        double enemyAbsoluteBearing = bot.target.guessAbsoluteBearing();
        double enemyDistance = bot.target.guessDistance();
        Point2d enemyLocation = KrillUtil.vectorToLocation(enemyAbsoluteBearing, enemyDistance, robotLocation);
        
        double flattenerFactor = 0.05;
        if (Math.random() < flattenerFactor) {
            movementLateralAngle *= -1;
        }
        Point2d robotDestination = null;
        double tries = 0;
        do {
            robotDestination = KrillUtil.vectorToLocation(KrillUtil.getBearing(enemyLocation, robotLocation) + movementLateralAngle,
                                                enemyDistance * (1.1 - tries / 100.0), enemyLocation);
            tries++;
        } while (tries < 100 && !new RoundRectangle2D.Double(30, 30, bot.getBattleFieldWidth() - 60, bot.getBattleFieldHeight() - 60, 75, 75).contains(robotDestination));
        
        double angle = robocode.util.Utils.normalRelativeAngle(KrillUtil.getBearing(robotLocation, robotDestination) - bot.getHeadingRadians());
        double turnAngle = Math.atan(Math.tan(angle));
        bot.setTurnRightRadians(turnAngle+Math.toRadians(KrillUtil.rand.nextInt(15))*(KrillUtil.rand.nextInt(1) == 1 ? 1: -1));
        bot.setAhead(robotLocation.distance(robotDestination) * (angle == turnAngle ? 1 : -1));
    }
}
        